package pers.w.chaptertalk.funs;

import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

import androidx.annotation.NonNull;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import pers.w.chaptertalk.R;
import pers.w.chaptertalk.funs.db.Tab_Base;
import pers.w.chaptertalk.funs.db.Tab_Book;
import pers.w.chaptertalk.funs.db.Tab_Chapter;

public class ChapterThread extends Thread implements Runnable, IReader {


    public boolean isStop() {
        return stop;
    }

    public void cancel() {
        this.stop = true;
    }

    private boolean stop = false;
    private List<Map<String, String>> chapter_list;
    private BookInfo bookInfo;
    private Handler handler;
    private boolean noWhile;
    private boolean insertSql;
    private Context context;
    private long bookID;
    private boolean fillBook = false;


    public ChapterThread(@NonNull BookInfo bookInfo,@NonNull List<Map<String, String>> chapter_list, Handler handler) {
        this.bookInfo = bookInfo;
        this.chapter_list = chapter_list;
        this.handler = handler;
        this.noWhile = false;
        insertSql = false;
        context = null;
        bookID = 0;
    }

    private ChapterThread(@NonNull BookInfo bookInfo,@NonNull List<Map<String, String>> chapter_list, Handler handler, boolean noWhile) {
        this(bookInfo, chapter_list, handler);
        this.noWhile = noWhile;
    }

    /**
     * 这个构造是查询后直接加入数据库
     *
     * @param insertSql true的时候必须传入context 和bookid
     */
    public ChapterThread(@NonNull BookInfo bookInfo, @NonNull List<Map<String, String>> chapter_list, Handler handler,
                         boolean noWhile, boolean insertSql, Context context, long bookID) {
        this(bookInfo, chapter_list, handler, noWhile);
        this.insertSql = insertSql;
        this.context = context;
        this.bookID = bookID;
    }
    public ChapterThread(@NonNull BookInfo bookInfo, @NonNull List<Map<String, String>> chapter_list, Handler handler,
                         boolean noWhile, boolean insertSql, Context context, long bookID,boolean fillBook) {
        this(bookInfo, chapter_list, handler, noWhile,insertSql,context,bookID);
        this.fillBook =fillBook;
    }
    @Override
    public void run() {
        getInfo();
    }

    public void getInfo() {
        final String uri = bookInfo.getFieldValue(R.string.info_uri);
        Document doc = null;
        while (!stop) {
            try {
                doc = Jsoup.connect(uri).timeout(5000).get();
                break;
            } catch (IOException e) {
                e.printStackTrace();
                doc = null;
                if (noWhile) {
                    if (handler != null) {
                        Message msg = handler.obtainMessage(HANDLER_ERROR);
                        handler.sendMessage(msg);
                    }
                    stop = true;
                    return;
                }
            }
        }

        if (Fun.isDebug()) Log.d("getChapter", uri + ": 开始获取章节");
        assert uri != null;
        Elements result_list;
        //if (0 == uri.indexOf(getString(R.string.天籁网))) {
                /*if (0 == uri.indexOf(getString(R.string.笔趣阁1)) || 0 == uri.indexOf(getString(R.string.笔趣阁2))) {
                    result_list = doc.select("img");
                    if (null != result_list && result_list.size() > 0 && ((String) bookinfo.getFieldValue(R.string.info_img)).isEmpty()) {//没有图片地址，从这里读取一次
                        String imgUrl = result_list.get(0).attr("src");
                        if (0 == uri.indexOf(getString(R.string.笔趣阁2)))
                            imgUrl = "https://www.biqugg.com" + imgUrl;

                        bookinfo.setFieldValue(R.string.info_img, imgUrl);

                        new WebBmpThread(bookInfos) {
                            @Override
                            public void runOnUiThread(int position) {
                                Message msg_update_image = new Message();
                                msg_update_image.what = 2;
                                handler.sendMessage(msg_update_image);
                            }
                        }.start();

                    }
                    result_list = doc.select("div[id=intro]");
                    if (null != result_list && result_list.size() > 0 && ((String) bookinfo.getFieldValue(R.string.info_introduction)).isEmpty())
                        bookinfo.setFieldValue(R.string.info_introduction, result_list.get(0).text());
                }*/

        assert doc != null;

        if (fillBook || insertSql) {//同时把章节信息重新回填bookinfo,主动设置fillBook 或者insertSql要更新数据库的时候也读一次，后面用
            fillBook(uri, doc);
        }
        result_list = doc.select("dd");
        int i=0;
        if (0 == uri.indexOf(资源笔趣阁3) ||0 == uri.indexOf(资源笔趣阁4)) i=9;//这两个资源前面几个章节是最后章节，要去掉
        for (  ; i < result_list.size(); i++) {
            Map<String, String> chapter_map = new HashMap<>();

            Elements chapterElement = result_list.get(i).select("a");
            if (chapterElement.size() == 1) {
                chapter_map.put(Tab_Chapter.CHAPTERNAME,
                        chapterElement.get(0).text());
                String chapterUri = chapterElement.get(0).attr("href");
                if (null != chapterUri && chapterUri.indexOf(uri) != 0){//如果获得的章节地址是相对路径，转为绝对路径
                    if (0 == uri.indexOf(天籁)){
                        chapterUri = 天籁 +"/"+ chapterUri.substring(1);
                    }else if (0 == uri.indexOf(资源笔趣阁3)){
                        chapterUri = 资源笔趣阁3 +"/"+ chapterUri.substring(1);
                    } else if (0 == uri.indexOf(资源笔趣阁4)){
                        chapterUri = 资源笔趣阁4 +"/"+ chapterUri.substring(1);
                    }  else
                        chapterUri = uri + chapterUri;
                }
                chapter_map.put(Tab_Chapter.CHAPTERURI, chapterUri);
                chapter_map.put(Tab_Chapter.CHAPTERUPDATETIME, "");
                chapter_list.add(chapter_map);
            }
        }

        if (insertSql)
            insertSql();

        sendMsg();

        stop = true;
    }

    private void fillBook(String uri, Document doc) {
        BookInfo book = null;
        if (uri.indexOf(资源笔趣阁2) == 0) {
            book = handle_bqg(doc, BookThread.BQG2);
        } else if (uri.indexOf(资源笔趣阁1) == 0) {
            book = handle_bqg(doc, BookThread.BQG1);
        } else if (uri.indexOf(天籁) == 0) {
            book = handle_bqg(doc, BookThread.TIANLAI);
        }else if (uri.indexOf(资源笔趣阁3) == 0) {
            book = handle_bqg(doc, BookThread.BQG3);
        }else if (uri.indexOf(资源笔趣阁4) == 0) {
            book = handle_bqg(doc, BookThread.BQG4);
        }
        if (book!=null){
            bookInfo.getBookifoMap().putAll(book.getBookifoMap());
        }
    }

    private void insertSql() {
        if (chapter_list.size() > 0) {
            if (bookID > 0) {//存在数据库中
                Tab_Book tab_book = new Tab_Book(context);
                long addCount =  tab_book.getTab_chapter().add(bookID, chapter_list);
                chapter_list.clear();
                chapter_list.addAll(tab_book.getTab_chapter().get_chapters(bookID)) ;//有新数据，重新从数据库获得完整数据，否则，返回的list的chapter id 可能为null
                if (addCount>0){//更新一下最后一章信息
                    tab_book.update(bookInfo);
                }
                tab_book.close();
            } else {
                for (int i = 0; i < chapter_list.size(); i++) {
                    chapter_list.get(i).put(Tab_Base.CHAPTER_ID, String.valueOf(i));
                }
            }
        }
    }

    public static BookInfo handle_bqg(Document doc, int what) {
        Elements result_list;
        result_list = doc.select("div[id=intro]");
        if (null != result_list && result_list.size() > 0) {
            BookInfo book = new BookInfo();
            book.setFieldValue(R.string.info_introduction, result_list.get(0).text());

            result_list = doc.select("img");
            String imgUrl = result_list.get(0).attr("src");
            if (BookThread.BQG2 == what)
                imgUrl = IReader.资源笔趣阁2+ imgUrl;
            else if(BookThread.BQG3 == what)
                imgUrl = IReader.资源笔趣阁3+ imgUrl;
            else if(BookThread.BQG4 == what)
                imgUrl = IReader.资源笔趣阁4+ imgUrl;
            book.setFieldValue(R.string.info_img, imgUrl);

            book.setFieldValue(R.string.info_uri, doc.location());

            result_list = doc.select("div[id=info]");
            Element info = result_list.get(0);

            book.setFieldValue(R.string.info_name, info.child(0).text());
            String text;
            switch (what){
                case BookThread.BQG1:
                    text = info.child(1).child(0).text();
                    book.setFieldValue(R.string.info_author, text);
                    text = info.child(3).text();
                    book.setFieldValue(R.string.info_lastUpdateTime, text.substring(text.indexOf("：") + 1));
                    book.setFieldValue(R.string.info_lastChapterName, info.child(4).child(0).text());
                    book.setFieldValue(R.string.info_type, "未分类");


                    text = doc.select("div.con_top").get(0).text();
                    int index = text.indexOf(">");
                    if (index != -1) {
                        text = text.substring(index + 2, index + 6);
                        book.setFieldValue(R.string.info_type, text);
                    }
                    break;
                case BookThread.BQG2:
                case BookThread.BQG3:
                    text = info.child(1).text();
                    book.setFieldValue(R.string.info_author, text.substring(text.indexOf("：") + 1));
                    text = info.child(3).text().replace(":","：");

                    book.setFieldValue(R.string.info_lastUpdateTime, text.substring(text.indexOf("：") + 1));
                    book.setFieldValue(R.string.info_lastChapterName, info.child(4).child(0).text());
                    book.setFieldValue(R.string.info_type, "未分类");
                    break;


                case BookThread.TIANLAI:
                    text = info.child(1).text();
                    book.setFieldValue(R.string.info_author, text.substring(text.indexOf("：") + 1));
                    text = info.child(3).text();
                    book.setFieldValue(R.string.info_lastUpdateTime, text.substring(text.indexOf("：") + 1));
                    book.setFieldValue(R.string.info_lastChapterName, info.child(4).child(0).text());
                  //  book.setFieldValue(R.string.info_type, "未分类");
                    text = doc.select("div.con_top").get(0).child(1).text();
                    book.setFieldValue(R.string.info_type, text);

                    break;
            }

            return book;
        }
        return null;
    }

    /**
     *
     */
    private void sendMsg() {
        if (handler != null) {
            Message msg = handler.obtainMessage(HANDLER_CHAPTER_THREAD_MSG, chapter_list.size(), 0, chapter_list);
            handler.sendMessage(msg);
            if (Fun.isDebug()) Log.d("sendMsg", "sendMsg: ");
        }
    }
}
